package org.shj.basic

//使用样例类做模式匹配时，如果后期又增加了一个子类，则原先的匹配语句中就会漏掉这个新增的
//子类，可以使用 sealed 来修饰超类，这样，新增的子类必须定义在与超类相同的文件中
//并且如果没有在原来匹配的语句中加入新类的话，编译器会给出错误信息
sealed class Animal
case class Dog(name : String) extends Animal
case class Cat(name : String) extends Animal

object PatterMatchDemo {
  def main(args: Array[String]): Unit = {
    def getSalary(name : String, age : Int){
      name match{
        case "Hadoop" => println("$150000")
        case "Spark" => println("$300000")
        case _ if name == "Scala" => println("$120000")
        case _name if age > 5 => println(_name + "$7890")
        case _ => println("$2323")
      }
    }
    getSalary("Scala", 6)
    getSalary("asdf", 6)
    getSalary("Java", 5)
    
    def matchType(msg : Any){
      msg match{
        case i : Int => println("Integer")
        case s : String => println("String")
        case d : Double => println("Double")
        case a : Array[Int] => println("Array")
        case _ => println("Unkown Type")
      }
    }
    
    matchType(100.1)
    matchType(Array(1,2))
    
    def matchArray(param : Array[String]){
      param match{
        case Array("Scala") => println("One element")
        case Array("Scala", "Java") => println("Two element")
        case Array("Spark", _*) => println("Multiple element")
        case _ => println("Doesn't match")
      }
    }
    
    matchArray(Array("Scala"))
    matchArray(Array("Scala", "Python"))
    
    
    def matchClass(cls : Animal){
      cls match{
        case Cat(name) => println("cat is " + name)
        case Dog(name) => println(name + " is Dog")
        case _ => println("Unknow class")
      }
    }
    
    matchClass(Cat("Tome"))
    matchClass(Dog("Wang Cai"))
    
    getValue("Spark", Map("Spark" -> "aa", "Hadoop" -> "bbb"))
    getValue("Python", Map("Spark" -> "aa", "Hadoop" -> "bbb"))
  }
  
  def getValue(key : String, map : Map[String, String]){
    map.get(key) match{
      case Some(value) => println("Key: " + key + "; value=" + value)
      case None => println("not found")
    }
  }
}